package com.hwd.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwd.srb.core.enmu.BorrowAuthEnum;
import com.hwd.srb.core.enmu.BorrowerStatusEnum;
import com.hwd.srb.core.enmu.IntegralEnum;
import com.hwd.srb.core.mapper.BorrowerAttachMapper;
import com.hwd.srb.core.mapper.BorrowerMapper;
import com.hwd.srb.core.mapper.UserInfoMapper;
import com.hwd.srb.core.mapper.UserIntegralMapper;
import com.hwd.srb.core.pojo.entity.Borrower;
import com.hwd.srb.core.pojo.entity.BorrowerAttach;
import com.hwd.srb.core.pojo.entity.UserInfo;
import com.hwd.srb.core.pojo.entity.UserIntegral;
import com.hwd.srb.core.pojo.vo.BorrowerApprovalVO;
import com.hwd.srb.core.pojo.vo.BorrowerAttachVO;
import com.hwd.srb.core.pojo.vo.BorrowerDetailVO;
import com.hwd.srb.core.pojo.vo.BorrowerVO;
import com.hwd.srb.core.service.BorrowerService;
import com.hwd.srb.core.service.DictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author 黄伟东/Victor
 * @since 2022-03-10
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Resource
    private DictService dictService;

    @Resource
    private UserIntegralMapper userIntegralMapper;

    /**
     * 根据userId查询借款人状态
     *
     * @param userId 用户id
     * @return java.lang.Integer
     */
    @Override
    public BorrowerStatusEnum getBorrowerStatusByUserId(Long userId) {

        LambdaQueryWrapper<Borrower> queryWrapper = new LambdaQueryWrapper<Borrower>()
                .select(Borrower::getStatus)
                .eq(Borrower::getUserId, userId);

        Borrower borrower = baseMapper.selectOne(queryWrapper);

        if (borrower == null) {
            return BorrowerStatusEnum.NO_AUTH;
        }

        return borrower.getStatus();
    }

    /**
     * 保存借款人信息
     *
     * @param borrowerVO 借款人信息对象
     * @param userId     用户id
     */
    @Override
    public void saveBorrowerVOByUserId(BorrowerVO borrowerVO, Long userId) {
        // 获取用户基本信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        // 保存额度申请信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(Long.parseLong(userInfo.getIdCard()));
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN);
//        borrower.setIsMarry(borrowerVO.getMarry() ? 1 : 0);
        baseMapper.insert(borrower);

        // 获取借款人自增主键
        Long borrowerId = borrower.getId();

        // 保存额度申请附件信息
        borrowerVO.getBorrowerAttachList().forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrowerId);
            borrowerAttachMapper.insert(borrowerAttach);
        });

        // 更新userInfo中的借款人认证状态borrow_auth_status
        userInfo.setBorrowAuthStatus(BorrowAuthEnum.AUTH_RUN);
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 根据关键字查询借款人列表(额度申请)
     *
     * @param pageParam 分页查询参数，page，size
     * @param keyword   关键字
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.hwd.srb.core.pojo.entity.Borrower>
     */
    @Override
    public IPage<Borrower> listPage(Page<Borrower> pageParam, String keyword) {

        // 关键字为空
        if (StringUtils.isEmpty(keyword)) {
            return baseMapper.selectPage(pageParam, null);
        }

        LambdaQueryWrapper<Borrower> queryWrapper = new LambdaQueryWrapper<Borrower>()
                .like(Borrower::getName, keyword)
                .or().like(Borrower::getMobile, keyword)
                .or().like(Borrower::getIdCard, keyword)
                .orderByDesc(Borrower::getId);

        return baseMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 根据id查询借款人详情(额度申请)
     *
     * @param borrowerId 借款人id
     * @return com.hwd.srb.core.pojo.vo.BorrowerDetailVO
     */
    @Override
    public BorrowerDetailVO show(Long borrowerId) {

        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();

        // 查询borrower表，借款人(额度申请)基本信息
        Borrower borrower = baseMapper.selectById(borrowerId);

        BeanUtils.copyProperties(borrower, borrowerDetailVO);
//        borrowerDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowerDetailVO.setEducation(dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation()));
//        borrowerDetailVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));
        borrowerDetailVO.setIdCard(borrower.getIdCard() + "");
        borrowerDetailVO.setCreateTime(borrower.getCreateTime());
//        borrowerDetailVO.setMarry(borrower.getIsMarry() == 1 ? "已婚" : "未婚");
        borrowerDetailVO.setIndustry(dictService.getNameByParentDictCodeAndValue("industry", borrower.getIndustry()));
        borrowerDetailVO.setIncome(dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome()));
        borrowerDetailVO.setReturnSource(dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource()));
        borrowerDetailVO.setContactsRelation(dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation()));

        // 查询borrowerAttach表，借款人额度申请附件信息
        LambdaQueryWrapper<BorrowerAttach> borrowerAttachQueryWrapper = new LambdaQueryWrapper<BorrowerAttach>()
                .eq(BorrowerAttach::getBorrowerId, borrowerId);
        List<BorrowerAttach> borrowerAttaches = borrowerAttachMapper.selectList(borrowerAttachQueryWrapper);
        List<BorrowerAttachVO> borrowerAttachVOS = borrowerAttaches.stream().map(borrowerAttache -> {
            BorrowerAttachVO borrowerAttachVO = new BorrowerAttachVO();
            BeanUtils.copyProperties(borrowerAttache, borrowerAttachVO);
            return borrowerAttachVO;
        }).collect(Collectors.toList());

        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOS);

        return borrowerDetailVO;
    }

    /**
     * 借款额度审核
     *
     * @param borrowerApprovalVO 借款人审核数据对象
     */
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        // 获取审核数据，借款人id
        Long borrowerId = borrowerApprovalVO.getBorrowerId();

        // 根据借款人id查询用户id
        Borrower borrower = baseMapper.selectById(borrowerId);
        Long userId = borrower.getUserId();

        List<Integer> integerList = new ArrayList<>();
        // A 新增user_integral用户积分数据
        // 基本分
        Integer infoIntegral = insertIntegral(userId, IntegralEnum.BORROWER_INFO, borrowerApprovalVO.getInfoIntegral());
        integerList.add(infoIntegral);

        // 身份证分 +30
        Integer idCardIntegral = insertIntegral(userId, IntegralEnum.BORROWER_ID_CARD, borrowerApprovalVO.getIsIdCardOk());
        integerList.add(idCardIntegral);

        // 车分 +60
        Integer carIntegral = insertIntegral(userId, IntegralEnum.BORROWER_CAR, borrowerApprovalVO.getIsCarOk());
        integerList.add(carIntegral);

        // 房分 +100
        Integer houseIntegral = insertIntegral(userId, IntegralEnum.BORROWER_HOUSE, borrowerApprovalVO.getIsHouseOk());
        integerList.add(houseIntegral);

        // 计算积分
        BigDecimal totalIntegral = getBigDecimal(integerList);

        // B 修改user_info用户的“认证状态”,总积分"integral"
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setBorrowAuthStatus(BorrowAuthEnum.AUTH_OK);
        userInfo.setIntegral(totalIntegral.intValue());
        userInfoMapper.updateById(userInfo);

        // C 修改borrower借款人"认证状态"()
        borrower.setStatus(BorrowerStatusEnum.AUTH_OK);
        baseMapper.updateById(borrower);


    }

    private BigDecimal getBigDecimal(List<Integer> integerList) {
        final BigDecimal[] sum = {new BigDecimal("0")};
        integerList.stream().filter(Objects::nonNull)
                .forEach(i -> sum[0] = sum[0].add(new BigDecimal(i + "")));
        return sum[0];
    }


    /**
     * 根据用户id，积分枚举类型新增user_integral用户积分数据
     *
     * @param userId       用户id
     * @param integralEnum 积分枚举类型
     * @param isOK         是否添加记录
     * @return java.lang.Integer 本次添加的积分，isOK为false时返回null
     */
    private Integer insertIntegral(Long userId, IntegralEnum integralEnum, Boolean isOK) {
        if (!isOK) {
            return null;
        }
        UserIntegral userIntegral = new UserIntegral();
        Integer integral = integralEnum.getIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(integral);
        userIntegral.setContent(integralEnum.getContent());
        userIntegralMapper.insert(userIntegral);
        return integral;
    }

    /**
     * 根据用户id，积分枚举类型，积分值新增user_integral用户积分数据
     *
     * @param userId       用户id
     * @param integralEnum 积分枚举类型
     * @param value        添加的积分值
     * @return java.lang.Integer 本次添加的积分
     */
    private Integer insertIntegral(Long userId, IntegralEnum integralEnum, Integer value) {

        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(value);
        userIntegral.setContent(integralEnum.getContent());
        userIntegralMapper.insert(userIntegral);

        return value;
    }

}
